﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using CoolCode.Entities;
using CoolCode.Services;
using CoolCode.OfficeToolkit.Excel;
using CoolCode.Web;

namespace CoolCode.WebServices
{

    public enum ProductExcelColumn
    {
        [AttachString("")]
        None,    //占位符 
        [AttachString("产品序号")]
        Line,		// 序号
        [AttachString("产品编号")]
        ProductID, // 产品编号
        [AttachString("产品规格")]
        ProductSpec, // 产品规格
        [AttachString("检验员")]
        Checker, // 检验员
        [AttachString("检验时间")]
        CheckDate, // 检验时间
        [AttachString("胶面")]
        Face,    // 胶面
        [AttachString("囊")]
        Burse,   // 囊
        [AttachString("缩腰件")]
        Drawback,// 缩腰件
        [AttachString("外观")]
        Appearance, // 外观
        [AttachString("胶面外径（远/近）")]
        OutsideDiameter,  // 胶面  
        [AttachString("锥体高度")]
        ConeHeight,// 锥体高度 
        [AttachString("球囊长度")]
        SacculusLength,// 球囊长度 
        [AttachString("球囊伸长长度")]
        SacculusStretch,// 球囊伸长长度 
        [AttachString("220KPa压力测试（外径/长度）")]
        StressTest,// 220KPa压力测试 度
        [AttachString("夹层")]
        Interlayer, // 夹层
        [AttachString("脱胶、反胶")]
        Degumming, // 脱胶、反胶
        [AttachString("备注")]
        Remark, // 备注
        [AttachString("状态")]
        Status, // 状态：O出库，I在仓库 
    }

    public class ExportService : IExportService<Inspection>
    {
        private InspectionService _Service;
        public InspectionService Service
        {
            get
            {
                if (_Service == null)
                {
                    _Service = new InspectionService();
                }
                return _Service;
            }
        }

        public string ExportOutbound(Guid guid, out ExportResult message)
        {
            string fileName = guid.ToString() + ".xls";
            var list = Service.ListOutbound(guid);
            return ExportToExcel(list, fileName, false, out message);
        }

        public string Export(List<Inspection> list, out ExportResult message)
        {
            string fileName = DateTime.Now.ToString("yyyy-MM-dd HHmmss fff") + ".xls";
            return ExportToExcel(list, fileName, true, out message);
        }


        public string ExportToExcel(List<Inspection> list, string fileName, bool replaceIfExist, out ExportResult message)
        {
            message = ExportResult.Success;
            string savePath = Path.Combine(Utility.GetMapPath("~/Output/"), fileName);
            if (list.Count == 0)
            {
                message = ExportResult.Empty;
                return savePath;
            }
            string template = Utility.GetMapPath("~/Content/excel/Template.xls");
            if (!File.Exists(template))
            {
                message = ExportResult.TemplateNotFound;
                return savePath;
            }
            bool fileExist = File.Exists(savePath);
            if (fileExist)
            {
                if (replaceIfExist)
                {
                    File.Delete(savePath);
                    fileExist = false;
                }
                else
                {
                    message = ExportResult.FileExist;
                    return savePath;
                }
            }

            if (!fileExist)
            {
                ExcelHelper excel = new ExcelHelper(template, savePath);
                int beginCol = (int)ProductExcelColumn.Line;
                int endCol = (int)ProductExcelColumn.Remark;
                int row = 1;
                int count = list.Count;
                int width = endCol;
                // excel.SetCells(row, 5, "检查点");

                row++;

                row++;
                object[,] values = new object[count, width];
                for (int i = 0; i < count; i++)
                {
                    var product = list[i];
                    values[i, (int)ProductExcelColumn.Line - 1] = product.Line;
                    values[i, (int)ProductExcelColumn.ProductID - 1] = product.ProductID;
                    values[i, (int)ProductExcelColumn.ProductSpec - 1] = product.ProductSpec;
                    values[i, (int)ProductExcelColumn.Checker - 1] = product.Checker;
                    values[i, (int)ProductExcelColumn.CheckDate - 1] = product.CheckDate;
                    values[i, (int)ProductExcelColumn.Face - 1] = product.Face;
                    values[i, (int)ProductExcelColumn.Burse - 1] = product.Burse;
                    values[i, (int)ProductExcelColumn.Drawback - 1] = product.Drawback;
                    values[i, (int)ProductExcelColumn.Appearance - 1] = product.Appearance;
                    values[i, (int)ProductExcelColumn.OutsideDiameter - 1] = product.OutsideDiameter;
                    values[i, (int)ProductExcelColumn.ConeHeight - 1] = product.ConeHeight;
                    values[i, (int)ProductExcelColumn.SacculusLength - 1] = product.SacculusLength;
                    values[i, (int)ProductExcelColumn.SacculusStretch - 1] = product.SacculusStretch;
                    values[i, (int)ProductExcelColumn.StressTest - 1] = product.StressTest;
                    values[i, (int)ProductExcelColumn.Interlayer - 1] = product.Interlayer;
                    values[i, (int)ProductExcelColumn.Degumming - 1] = product.Degumming;
                    values[i, (int)ProductExcelColumn.Remark - 1] = product.Remark;
                }
                //excel.SetRowHeight(row,  count, 34.5);
                if (count > 1)
                {
                    excel.CopyRows(1, row, count - 1);
                    excel.DrawBox(row, 1, count, width);
                    excel.SetBorders(row, 1, count, width);
                }
                excel.SetCells(row, 1, values);

                //summary
                row +=count +2;
                string summary= string.Empty ;
                int dateCount = list.GroupBy(c=> c.CheckDate ).Count();
                if(dateCount ==1)
                    summary += list.First().CheckDate.ToString(Config.DateFormat);
                summary += string.Format("总检，共{0}条，", count ) ;
               var groupbySpec =  list.GroupBy(c=> c.ProductSpec ).Select(c=> "Φ" +c.Key + "×"+ c.Count()) ;
               summary += string.Join("，",groupbySpec.ToArray()) ;
               //excel.SetRowHeight(row, 34.5);
               excel.SetCells(row, 5, summary);
               excel.SetBold(row, 5, 11);
                excel.SaveAsFile(savePath);
            }
            return savePath;

        }
    }
}
